 package com.oanda.blackberry.view;
 
 import com.oanda.blackberry.OandaBlackBerryApplication;
 import com.oanda.blackberry.net.ConnectionManager;
 import com.oanda.blackberry.restapi.PricePoint;
 import com.oanda.blackberry.restapi.Quote;
 import com.oanda.blackberry.restapi.Rate;
 import com.oanda.blackberry.ui.ColoredRadioButtonField;
 import com.oanda.blackberry.ui.OandaMainScreen;
 import com.oanda.blackberry.ui.SpacerField;
 import com.oanda.blackberry.util.AbstractViewPanel;
 import com.oanda.blackberry.util.DefaultController;
 import com.oanda.blackberry.util.Model;
 import com.oanda.blackberry.util.PropertyChangeEvent;
 import com.oanda.blackberry.util.Settings;
 import com.oanda.blackberry.util.log.Logger;
 import java.io.InputStream;
 import java.util.Timer;
 import java.util.TimerTask;
 import javax.microedition.io.Connector;
 import javax.microedition.io.InputConnection;
 import net.rim.device.api.system.Application;
 import net.rim.device.api.system.Bitmap;
 import net.rim.device.api.ui.Field;
 import net.rim.device.api.ui.FieldChangeListener;
 import net.rim.device.api.ui.Font;
 import net.rim.device.api.ui.Graphics;
 import net.rim.device.api.ui.Manager;
 import net.rim.device.api.ui.MenuItem;
 import net.rim.device.api.ui.Screen;
 import net.rim.device.api.ui.UiApplication;
 import net.rim.device.api.ui.component.Dialog;
 import net.rim.device.api.ui.component.LabelField;
 import net.rim.device.api.ui.component.Menu;
 import net.rim.device.api.ui.component.NullField;
 import net.rim.device.api.ui.component.ObjectChoiceField;
 import net.rim.device.api.ui.component.RadioButtonGroup;
 import net.rim.device.api.ui.container.HorizontalFieldManager;
 import net.rim.device.api.ui.container.MainScreen;
 import net.rim.device.api.ui.container.VerticalFieldManager;
 import net.rim.device.api.ui.decor.BackgroundFactory;
 import org.json.me.JSONArray;
 import org.json.me.JSONException;
 import org.json.me.JSONObject;
 
 public class HistoryView extends OandaMainScreen
   implements AbstractViewPanel
 {
   DefaultController controller;
   String[] values = { "MaxBid", "MinBid", "Min/Max Ribbon", "Candle Stick" };
   ObjectChoiceField chartType = new ObjectChoiceField("Chart type:", this.values);
 
   ColoredRadioButtonField ribbon = new ColoredRadioButtonField(14540253, "Min/Max");
   ColoredRadioButtonField candle = new ColoredRadioButtonField(14540253, "Candle Stick");
   RadioButtonGroup chartTypeGroup = new RadioButtonGroup();
 
   String[] choices = { "5 sec", "30 sec", "1 min", "5 min", "15 min", "1 hour", "1 day" };
   int[] scales = { 5, 30, 60, 300, 150, 3600, 86400 };
 
   IntervaButtonField h5s = new IntervaButtonField(16119285, " 5 sec ");
   IntervaButtonField h30s = new IntervaButtonField(16119285, " 30 sec ");
   IntervaButtonField h1m = new IntervaButtonField(16119285, " 1 min ");
   IntervaButtonField h5m = new IntervaButtonField(16119285, " 5 min ");
   IntervaButtonField h15m = new IntervaButtonField(16119285, " 15 min");
   IntervaButtonField h1h = new IntervaButtonField(16119285, " 1 hour ");
   IntervaButtonField h1d = new IntervaButtonField(16119285, " 1 day ");
   private ChartField lineGraphField;
   VerticalFieldManager graphFieldManager = new VerticalFieldManager();
   Rate tempRate;
   String symbol;
   int precious = 5;
   Quote quote;
   Timer updateTimer = new Timer();
   TimerTask updateTask;
   int UPDATE_TIME = 5000;
 
   MenuItem backMenu = new MenuItem("Back", 10, 1000)
   {
     public void run() {
       HistoryView.this.onClose();
     }
   };
 
   public HistoryView(DefaultController controller)
   {
     this(controller, 0L);
   }
 
   public HistoryView(DefaultController controller, long style)
   {
     this.controller = controller;
 
     getMainManager().setBackground(BackgroundFactory.createBitmapBackground(Bitmap.getBitmapResource("history-bg-480x290.png")));
 
     add(new SpacerField(480, 30));
 
     HorizontalFieldManager buttons = new HorizontalFieldManager();
     setButtonsFont();
     buttons.add(new SpacerField(30, 20));
     buttons.add(this.h5s);
     buttons.add(new SpacerField(10, 20));
     buttons.add(this.h30s);
     buttons.add(new SpacerField(10, 20));
     buttons.add(this.h1m);
     buttons.add(new SpacerField(10, 20));
     buttons.add(this.h5m);
     buttons.add(new SpacerField(10, 20));
     buttons.add(this.h15m);
     buttons.add(new SpacerField(10, 20));
     buttons.add(this.h1h);
     buttons.add(new SpacerField(10, 20));
     buttons.add(this.h1d);
     add(buttons);
 
     add(this.graphFieldManager);
 
     add(new SpacerField(480, 1));
 
     this.chartTypeGroup.add(this.ribbon);
     this.chartTypeGroup.add(this.candle);
     HorizontalFieldManager types = new HorizontalFieldManager();
     types.add(new SpacerField(160, 18));
     types.add(this.ribbon);
     types.add(new SpacerField(10, 18));
     types.add(this.candle);
     add(types);
 
     this.chartTypeGroup.setChangeListener(new FieldChangeListener()
     {
       public void fieldChanged(Field field, int context)
       {
         HistoryView.this.chartTypeFieldChanged();
       }
     });
     setSelectedIntervalButtonField(" 1 min ");
   }
 
   private void chartTypeFieldChanged()
   {
     if (this.quote != null) {
       this.controller.setHistoryChartTypeIndex(this.chartTypeGroup.getSelectedIndex());
       Model.getModel(); this.controller.history(this.quote, getGranularity(Model.getModel().getSettings().getHistoryTimeInterval()), Model.getHistoryPoints(this.chartTypeGroup.getSelectedIndex()));
     }
   }
 
   private void setGrapchData(final Rate rate)
   {
     UiApplication.getUiApplication().invokeLater(new Runnable() {
       private final Rate _rate=rate;
 
       public void run() {
         PricePoint[] p = this._rate.getPricePoints();
         HistoryView.this.tempRate = this._rate;
         if (p.length == 0) {
           DefaultController.inform("p.length == 0");
           return;
         }
 
         int[] colors = { 32768 };
 
         int chType = HistoryView.this.chartTypeGroup.getSelectedIndex();
 
         if (ConnectionManager.getUrl().startsWith("devic")) {
           PricePoint[] pp = HistoryView.this.loadDataFromFile();
           if (pp != null)
             //HistoryView.access$102(HistoryView.this, new ChartField(pp, HistoryView.this.symbol, 8, chType));
        	   HistoryView.this.lineGraphField = new ChartField(pp, HistoryView.this.symbol, 8, chType); 
         } else {
           //HistoryView.access$102(HistoryView.this, new ChartField(p, HistoryView.this.symbol, HistoryView.this.precious, chType));
        	 HistoryView.this.lineGraphField = new ChartField(p, HistoryView.this.symbol, HistoryView.this.precious, chType);
         }
 
         HistoryView.this.graphFieldManager.deleteAll();
 
         HistoryView.this.graphFieldManager.add(new NullField(36028797018963968L));
         HistoryView.this.graphFieldManager.add(HistoryView.this.lineGraphField);
         HistoryView.this.graphFieldManager.add(new NullField(36028797018963968L));
       } } );
   }
 
   private void setRate(Rate rate) {
     if (rate == null) return;
     if ((rate != null) && (rate.getPricePoints() == null)) return;
     setGrapchData(rate);
   }
 
   public void modelPropertyChange(final PropertyChangeEvent evt)
   {
     if (evt.getPropertyName().equals("HistoryException")) {
       if (this.tempRate == null) {
         String message = "error occured";
         if ((evt.getNewValue() != null) && ((evt.getNewValue() instanceof String))) {
           message = (String)evt.getNewValue();
         }
 
         diplayError(message, 3000);
 
         final String fMessage = message;
         Runnable r = new Runnable() {
           private final String _fMessage=fMessage;
 
           public void run() { String askText = "Retry?";
             if ((this._fMessage != null) && (this._fMessage.length() > 0)) {
               askText = askText + "(" + this._fMessage + ")";
             }
             int i = Dialog.ask(3, askText, 4);
             if ((i == 4) && 
               (HistoryView.this.quote != null)) {
               Model.getModel(); HistoryView.this.controller.history(HistoryView.this.quote, HistoryView.this.getGranularity(Model.getModel().getSettings().getHistoryTimeInterval()), Model.getHistoryPoints(Model.getModel().getHistoryChartTypeIndex()));
             }
           }
         };
         this.controller.invokeLater(r);
       }
 
     }
     else if (evt.getPropertyName().equals("setSettings")) {
       Object o = evt.getNewValue();
       if ((o != null) && ((o instanceof Settings))) {
         Settings s = (Settings)o;
         setSelectedIntervalButtonField(s.getHistoryTimeInterval());
         this.chartTypeGroup.setSelectedIndex(s.getHistoryChartTypeIndex());
       }
     }
     else if (evt.getPropertyName().equals("historyQuote")) {
       Object o = evt.getNewValue();
       if ((o != null) && ((o instanceof Quote))) {
         this.quote = ((Quote)o);
       }
     }
     else if (evt.getPropertyName().equals("historyPrecious")) {
       Object o = evt.getNewValue();
       if ((o != null) && ((o instanceof Integer))) {
         this.precious = ((Integer)o).intValue();
       }
     }
     else if (evt.getPropertyName().equals("historySymbol")) {
       UiApplication.getUiApplication().invokeLater(new Runnable() { 
    	   private final PropertyChangeEvent _evt=evt;
 
         public void run() { HistoryView.this.symbol = ((String)this._evt.getNewValue());
           HistoryView.this.updateTitle("Charts (" + HistoryView.this.symbol + ")"); }
       });
     }
     else if (evt.getPropertyName().equals("setRateHistory")) {
       if ((evt.getNewValue() != null) && ((evt.getNewValue() instanceof Rate))) {
         this.controller.pushScreen(this);
         Rate rate = (Rate)evt.getNewValue();
         setRate(rate);
       } else {
         DefaultController.inform("Error in hangling rates(1)");
       }
     }
     else if (evt.getPropertyName().equals("setRateHistoryUpdate")) {
       if ((evt.getNewValue() != null) && ((evt.getNewValue() instanceof Rate))) {
         Rate rate = (Rate)evt.getNewValue();
         if (this.lineGraphField != null)
           this.lineGraphField.updateGraphData(rate.getPricePoints());
       }
       else {
         DefaultController.inform("Error in hangling rates(2)");
       }
 
     }
     else if (evt.getPropertyName().equals("removeHistoryUpdateStatus")) {
       removeStatusField();
     }
     else if (evt.getPropertyName().equals("setHistoryUpdateStatus")) {
       if ((evt.getNewValue() != null) && ((evt.getNewValue() instanceof String)))
         setStatusField((String)evt.getNewValue());
     }
     else if ((evt != null) && (evt.getPropertyName().equals("showThrobber"))) {
       showThrobberPlain();
     } else if ((evt != null) && (evt.getPropertyName().equals("hideThrobber"))) {
       hideThrobber();
     }
     else if ((evt != null) && (evt.getPropertyName().equals("showHistoryView"))) {
       this.controller.pushScreen(this);
     }
   }
 
   PricePoint[] loadDataFromFile() {
     String json = "";
     StringBuffer b = new StringBuffer();
     try {
       InputConnection fileConnection = (InputConnection)Connector.open("cod://oanda/history.json-g30-p10.bin");
       InputStream fin = null;
       fin = fileConnection.openInputStream();
       if (fin == null) {
         DefaultController.inform("IS is null");
         return null;
       }
 
       int i = 0;
       while ((i = fin.read()) != -1)
         b.append((char)i);
     }
     catch (Exception ex) {
       return null;
     }
 
     json = b.toString();
     try {
       JSONObject o = new JSONObject(json);
       JSONArray a = o.getJSONArray("price_points");
       PricePoint[] pp = new PricePoint[a.length()];
       for (int i = 0; i < a.length(); i++) {
         JSONObject j = a.getJSONObject(i);
         pp[i] = new PricePoint(j.getLong("time"), (float)j.getDouble("open_bid"), (float)j.getDouble("open_ask"), (float)j.getDouble("close_bid"), (float)j.getDouble("close_ask"), (float)j.getDouble("max_bid"), (float)j.getDouble("max_ask"), (float)j.getDouble("min_bid"), (float)j.getDouble("min_ask"));
 
         Logger.log(Float.toString(pp[i].maxBid));
       }
       return pp;
     }
     catch (JSONException e) {
     }
     return null;
   }
 
   private void updateHistory()
   {
     if ((this.tempRate != null) && (UiApplication.getUiApplication().getActiveScreen().equals(this)))
       this.controller.updateHistory();
   }
 
   protected void onUiEngineAttached(boolean attached)
   {
     if (attached)
     {
       if (this.updateTimer == null) {
         this.updateTimer = new Timer();
       }
       if (this.updateTask == null) {
         this.updateTask = new TimerTask()
         {
           public synchronized void run()
           {
             if (OandaBlackBerryApplication.isInForeground)
             {
               HistoryView.this.updateHistory();
               HistoryView.this.controller.turnOnBacklight();
             }
             else
             {
               try
               {
                 wait();
               }
               catch (InterruptedException e)
               {
               }
             }
           }
         };
       }
       this.updateTimer.schedule(this.updateTask, 0L, this.UPDATE_TIME);
     } else {
       Logger.log("historyView on UI EngineAttached cancelling");
       if (this.updateTask != null) {
         this.updateTask.cancel();
         this.updateTask = null;
       }
       if (this.updateTimer != null) {
         Logger.log("cancelling");
         this.updateTimer.cancel();
         this.updateTimer = null;
         Logger.log("Canceled");
       }
     }
   }
 
   public void notifyTimerTask()
   {
     if (this.updateTask != null)
     {
       synchronized (this.updateTask)
       {
         this.updateTask.notifyAll();
       }
     }
   }
 
   public boolean onClose() {
     this.controller.popScreen(this);
     return true;
   }
 
   private void setButtonsFont()
   {
     UiApplication.getUiApplication().invokeLater(new Runnable() {
       public void run() {
         Font f = DefaultController.getComponentFont().derive(0, 16);
 
         HistoryView.this.h5s.setFont(f);
         HistoryView.this.h30s.setFont(f);
         HistoryView.this.h1m.setFont(f);
         HistoryView.this.h5m.setFont(f);
         HistoryView.this.h15m.setFont(f);
         HistoryView.this.h1h.setFont(f);
         HistoryView.this.h1d.setFont(f);
 
         HistoryView.this.ribbon.setFont(f);
         HistoryView.this.candle.setFont(f);
       }
     });
   }
 
   private void setSelectedIntervalButtonField(String title) {
     if (title == null) return;
 
     if (title.equals(this.h5s.getText()))
       this.h5s.setSelected(true);
     else {
       this.h5s.setSelected(false);
     }
     if (title.equals(this.h30s.getText()))
       this.h30s.setSelected(true);
     else {
       this.h30s.setSelected(false);
     }
     if (title.equals(this.h1m.getText()))
       this.h1m.setSelected(true);
     else {
       this.h1m.setSelected(false);
     }
     if (title.equals(this.h5m.getText()))
       this.h5m.setSelected(true);
     else {
       this.h5m.setSelected(false);
     }
     if (title.equals(this.h15m.getText()))
       this.h15m.setSelected(true);
     else {
       this.h15m.setSelected(false);
     }
     if (title.equals(this.h1h.getText()))
       this.h1h.setSelected(true);
     else {
       this.h1h.setSelected(false);
     }
     if (title.equals(this.h1d.getText()))
       this.h1d.setSelected(true);
     else
       this.h1d.setSelected(false);
   }
 
   public void historyIntervalChanged(String title)
   {
     Model.getModel(); int p = Model.getHistoryPoints(Model.getModel().getHistoryChartTypeIndex());
     this.controller.history(this.quote, getGranularity(title), p);
   }
 
   public int getGranularity(String title) {
     String[] choices = { "5 sec", "30 sec", "1 min", "5 min", "15 min", "1 hour", "1 day" };
     int[] scales = { 5, 30, 60, 300, 900, 3600, 86400 };
     int g = 0;
     if (title.indexOf(choices[0]) > -1) g = scales[0];
     if (title.indexOf(choices[1]) > -1) g = scales[1];
     if (title.indexOf(choices[2]) > -1) g = scales[2];
     if (title.indexOf(choices[3]) > -1) g = scales[3];
     if (title.indexOf(choices[4]) > -1) g = scales[4];
     if (title.indexOf(choices[5]) > -1) g = scales[5];
     if (title.indexOf(choices[6]) > -1) g = scales[6];
 
     return g;
   }
 
   protected void makeMenu(Menu menu, int instance)
   {
     menu.add(this.backMenu);
   }
 
   class IntervaButtonField extends LabelField
   {
     boolean isFocused = false;
 
     private boolean selected = false;
     int color;
     String title;
 
     IntervaButtonField(int color, String title)
     {
       super();
       this.color = color;
       this.title = title;
       setMargin(2, 2, 2, 2);
     }
 
     protected boolean keyChar(char key, int status, int time)
     {
       if (key == '\n') {
         HistoryView.this.setSelectedIntervalButtonField(this.title);
         HistoryView.this.graphFieldManager.deleteAll();
         HistoryView.this.tempRate = null;
         HistoryView.this.historyIntervalChanged(this.title);
         HistoryView.this.controller.setHistoryTimeInterval(this.title);
 
         return true;
       }
       return super.keyChar(key, status, time);
     }
 
     protected boolean trackwheelClick(int status, int time)
     {
       HistoryView.this.setSelectedIntervalButtonField(this.title);
       HistoryView.this.graphFieldManager.deleteAll();
       HistoryView.this.tempRate = null;
       HistoryView.this.historyIntervalChanged(this.title);
       HistoryView.this.controller.setHistoryTimeInterval(this.title);
 
       return true;
     }
 
     public boolean isFocusable()
     {
       return true;
     }
 
     public void setSelected(boolean selected) {
       this.selected = selected;
       invalidate();
     }
 
     protected void drawFocus(Graphics graphics, boolean on)
     {
       graphics.setColor(16119285);
       graphics.drawRoundRect(0, 0, getWidth(), getHeight(), 3, 3);
     }
 
     protected void onFocus(int direction) {
       this.isFocused = true;
       super.onFocus(direction);
       invalidate();
     }
 
     protected void onUnfocus() {
       this.isFocused = false;
       super.onUnfocus();
       invalidate();
     }
 
     public void paint(Graphics graphics) {
       if (this.selected) {
         graphics.setColor(7171437);
         graphics.fillRoundRect(0, 0, getWidth(), getHeight(), 5, 5);
         graphics.setColor(this.color);
       }
       else {
         graphics.setColor(this.color);
       }super.paint(graphics);
     }
 
     public boolean isSelectionCopyable()
     {
       return false;
     }
   }
}

